import {
  BASE_URL
} from '../../../http/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '', // 咨询师id
    index: '',
    charges: [], // 咨询方式
    date: '',
    price:'',
    time: '10:00:00', // 默认时间
    situation_desc: '无', // 情况说明，备注
    userid: '',
    chargesPro:[], // 咨询方式增强版
    today: '' //获取今天日期不让用户选择之前的日期
  },
  onDesc(e) {
    this.setData({
      situation_desc: e.detail.value // 更新页面的 oldUserpwd 数据
    });
  },


  // 选择咨询方式
  bindPickerChange(e) {
    this.setData({
      index: e.detail.value
    });
  },

  // 选择咨询时间
  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    });
  },

  // 立即预约
  onReserve() {
    if (this.data.index != '' && this.data.date != '') {
      var str = "您选择的咨询方式 " + this.data.chargesPro[this.data.index].value + "\r\n" + "预约时间是" + this.data.date
      wx.showModal({
        title: '确认预约',
        content: str,
        confirmText: '确认预约',
        cancelText: '再想想',
        success: (res) => {
          if (res.confirm) {
            // 用户点了“确认”
            // console.log(this.data.charges[this.data.index], this.data.date, this.data.situation_desc);
            console.log(this.data.id, this.data.userid);
            const userData = {
              reservation: {}
            };
            console.log(this.data.charges[this.data.index]);
            
            if (this.data && this.data.charges && this.data.index !== undefined) {
              userData.chargesid = this.data.charges[this.data.index].id;
              userData.price = this.data.charges[this.data.index].price;
            }
            
            userData.consultid = this.data.id;
            userData.userid = this.data.userid;
            userData.reservationTime =`${this.data.date} ${this.data.time}`;
            
            // 现在可以安全地给 userData.reservation 的属性赋值
            userData.reservation.reservationTime = `${this.data.date} ${this.data.time}`;
            userData.reservation.situationDesc = this.data.situation_desc;
            userData.reservation.userId = this.data.userid;
            userData.reservation.consultId = this.data.id;

            console.log(userData);
            wx.request({
              url: `${BASE_URL}/consultOrder`,
              method: 'POST',
              data: userData, // 使用变量传递数据
              header: {
                'content-type': 'application/json'
              },
              success(res) {
                console.log(res);
                if(res.data.code==200){
                  wx.showToast({
                    title: '添加成功',
                  })
                  wx.redirectTo({
                    url: '/my/pages/MyConsultations1/MyConsultations1?id='+userData.userid
                  })
                }
                
              },
            })

            wx.showToast({
              title: '预约成功',
              icon: 'success',
              duration: 2000
            });
            // 这里可以调用真正的预约接口
          } else if (res.cancel) {
            // 用户点了“取消”，什么也不做或给出提示
            console.log('用户取消预约');
          }
        }
      });
    } else {
      wx.showToast({
        title: '信息填写不完整',
        icon: 'error',
        duration: 2000,
        mask: true // 防止点击穿透
      });
    }
  },


  getCharges: function (id) {
    wx.request({
      url: `${BASE_URL}/consultCharges/consultId/${id}`,
      success: (res) => {
        const list = res.data.data
        this.setData({
          charges:list
        })

        const pickerList = list.map(item => ({
          id: item.id,
          value: item.classify.classifyname + "：" + item.price + "￥"
          // price:item.price
        }));

        this.setData({
          chargesPro: pickerList
        });

        console.log("咨询方式有：", this.data.charges);

      }
    })
  },

  // 设置当前日期
  getCurrentDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const today = `${year}-${month}-${day}`;
    this.setData({
      today: today // 设置今天的日期
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCurrentDate(); // 在页面加载时获取当前日期
    const id = options.id
    this.setData({
      id: id  // 设置咨询师 id
    })
    this.getCharges(id)
    const userInfo = wx.getStorageSync("userInfo")
    if (userInfo == null||userInfo.id==null) {
      wx.reLaunch({
        url: "/pages/login/login",
      });
      wx.showToast({
        title: "请登录",
        icon: 'error'
      });
      
    } else {
      this.setData({
        userid: userInfo.id
      })
    }

  },

})